package com.wang.interview.threads;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author: wang
 * @date: 2021/7/23 14:04
 * @description:
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("召唤神龙！");  // 所有被await的线程释放前会先执行这里
        });
        for (int i = 1; i <= 7; i++){
            final int i1 = i;
            new Thread(()->{
                System.out.println("收集到第+"+i1+"+颗龙珠！");
                try {
                    cyclicBarrier.await();    // 每await()一次就会将barrier屏障减一，到0就执行cyclicBarrier中的方法
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());        // 最后执行，
            },String.valueOf(i1)).start();
        }
    }
}
